/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_components/zhiqim_console.htm
 *
 * Zhiqim Console is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.manager.presenter;

import java.util.Collection;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.ZmlContexts;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.httpd.validate.ones.IsByteLen;
import org.zhiqim.httpd.validate.onex.IsUserCode;
import org.zhiqim.httpd.validate.onex.IsUserPass;
import org.zhiqim.httpd.validate.two.IsEqual;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.constants.CodeConstants;
import org.zhiqim.kernel.util.Randoms;
import org.zhiqim.manager.ZmrBootstrap;
import org.zhiqim.manager.ZmrPassworder;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dbo.ZmrAvatar;
import org.zhiqim.manager.dbo.ZmrOperator;

/**
 * 管理台个人中心控制器
 *
 * @version v1.0.0 @author zouzhigang 2017-6-5 新建与整理
 */
@AnAlias("ZmrProfilePresenter")
@AnIntercept("chkZmrLogin")
public class ZmrProfilePresenter implements CodeConstants
{
    /** 修改账号 */
    public static void doUpdateCode(HttpRequest request) throws Exception
    {
        request.addValidate(new IsUserCode("operatorCode", "账号要求2-16位字母数字或中文开头，特殊字符支持（._-`~!@#$%）"));
        request.addValidate(new IsByteLen("operatorPass", "密码为6-16位，请输入正确的密码", 6, 16));
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        String operatorCode = request.getParameter("operatorCode");
        String operatorPass = request.getParameter("operatorPass");
        
        ZmrOperator operator = ZmrBootstrap.getOperator();
        if(operator == null || !ZmrLoginPresenter.validatePassword(request, operator, operatorPass))
        {
            request.setResponseError("旧密码不正确");
            return;
        }
        
        String newPassSalt = Randoms.lettersDigitsSecure(64);
        ZmrPassworder passworder = ZmrBootstrap.getPassworder();
        String newPassword = passworder.encode(operatorCode, operatorPass, newPassSalt);
 
        operator.setOperatorCode(operatorCode);
        operator.setOperatorPass(newPassword);
        operator.setOperatorPassSalt(newPassSalt);
        ZmrBootstrap.saveOperator(operator);
        
        //刷新到会话管理器
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        sessionUser.setOperator(operator);
    }
    
    /** 修改密码 */
    public static void doUpdatePassword(HttpRequest request) throws Exception
    {
        request.addValidate(new IsByteLen("oldPassword", "密码为6-16位，请输入正确的旧密码", 6, 16));
        request.addValidate(new IsUserPass("newPassword", "新密码不合法，要求6-16位（大小写字母数字和特殊字符必须四选三）"));
        request.addValidate(new IsUserPass("newPassword2", "新密码确认不合法，要求6-16位（大小写字母数字和特殊字符必须四选三）"));
        request.addValidate(new IsEqual("newPassword", "newPassword2", "新密码和新密码确认不一致"));
        
        if (!request.chkValidate())
        {
            request.setResponseError(request.getAlertMsg());
            return;
        }
        
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        
        ZmrOperator operator = ZmrBootstrap.getOperator();
        if(operator == null || !ZmrLoginPresenter.validatePassword(request, operator, oldPassword))
        {
            request.setResponseError("旧密码不正确");
            return;
        }
        
        String newPassSalt = Randoms.lettersDigitsSecure(64);
        ZmrPassworder passworder = ZmrBootstrap.getPassworder();
        newPassword = passworder.encode(operator.getOperatorCode(), newPassword, newPassSalt);
 
        operator.setOperatorPass(newPassword);
        operator.setOperatorPassSalt(newPassSalt);
        ZmrBootstrap.saveOperator(operator);
        
        //刷新到会话管理器
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        sessionUser.setOperator(operator);
    }
    
    /** 查询系统头像 */
    public static String doQuerySysAvatar(HttpRequest request) throws Exception
    {
        Collection<ZmrAvatar> list = ZmrBootstrap.getAvatarList();
        
        return ZmlContexts.parseZmlPath(request, "/zview/zhiqim_manager/presenter/selSysAvatarInfo.zml", "list", list);
    }
    
    /** 修改为系统头像 */
    public static void doUpdateSysAvatar(HttpRequest request, long avatarId) throws Exception
    {
        if(avatarId < 1000000000001L || avatarId > 1000000000010L)
        {
            request.setResponseError("选择的头像不存在，请重新选择");
            return;
        }
        
        //保存到配置
        ZmrOperator operator = ZmrBootstrap.getOperator();
        operator.setOperatorAvatar(avatarId);
        ZmrBootstrap.saveOperator(operator);
        
        //刷新到会话管理器
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        sessionUser.setOperator(operator);
    }
    
    /** 修改为系统参数 */
    public static void doUpdateParam(HttpRequest request) throws Exception
    {
        String paramKey = request.getParameter("paramKey");
        String paramValue = request.getParameter("paramValue");
        
        if (!"rememberCode".equals(paramKey) && !"rememberPass".equals(paramKey)
            && !"verificationCode".equals(paramKey) && !"manageLogin".equals(paramKey))
        {
            request.setResponseError("选择的参数不正确");
            return;
        }
        
        if (!"true".equals(paramValue) && !"false".equals(paramValue))
        {
            request.setResponseError("选择的参数值不正确");
            return;
        }

        boolean value = "true".equals(paramValue);
        
        ZmrOperator operator = ZmrBootstrap.getOperator();
        if ("rememberCode".equals(paramKey))
        {//开启记住账号
            operator.setRememberCode(value);
            if (!value && operator.hasRememberPass())
            {//关闭的时候检查关闭记住密码
                operator.setRememberPass(false);
            }
        }
        else if ("rememberPass".equals(paramKey))
        {//开启记住密码的同时要记住账号
            operator.setRememberPass(value);
            operator.setRememberCode(true);
        }
        else if ("verificationCode".equals(paramKey))
        {//开启验证码
            operator.setVerificationCode(value);
        }
        else
        {//开启管理页
            operator.setManageLogin(value);
        }
        
        //保存到配置
        ZmrBootstrap.saveOperator(operator);
        
        //刷新到会话管理器
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        sessionUser.setOperator(operator);
    }
}
